import {
	GET,
	POST,
	POSTJSON,
	PUT,
	DELETE,
	POSTFORM
} from './index'
import wxUrlConfig from '@/common/config.js'

// 微信登录
const wxLoginManager = () => {
	return new Promise(resolve => {
		let that = this
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				if (loginRes.code) {
					var params = {
						'code': loginRes.code
					}
					
					authLogin(params).then(res => {
						resolve(true);
					});
				}
			}
		})
	})
}

// 9.登录 
const authLogin = params => {
	const url = '/Web/Account/AuthLogin.ashx'

	return new Promise(resolve => {
		POSTJSON(url, params).then(res => {
			if (res) {
				if (res.success === true) {

					// 1. 持久保存用户信息
					uni.setStorageSync('openid', res.data.openid)
					uni.setStorageSync('session_key', res.data.session_key)
					uni.setStorageSync('unionid', res.data.main_union_id)

					// 1. 存入token
					resolve(res.data)
				}
			}
		})
	})
}

// 4. 获取当前用户信息
const AccountUserInfo = paramsInfo => {

	var openid = uni.getStorageSync('openid');
	var unionid = uni.getStorageSync('unionid');
	var params = {
		openId: openid,
		unionId: unionid,
		avatar:paramsInfo.avatar,
		nickname:paramsInfo.nickname
	}
	const url = '/Web/Account/UserInfo.ashx'
	return new Promise(resolve => {
		POST(url, params).then(res => {
			
			if (res.success === true) {
				if (!res.data.avatar) {
					res.data.avatar = wxUrlConfig.normalAvatar;
				}

				// 1. 保存当前的用户信息
				getApp().globalData = res.data;
				getApp().globalData.userId = res.data.main_union_id;
				// 2. 抛出信息
				resolve(res.data)
			}
		})
	})
}

// 5. 获取当前用户登录状态
const memberHasLoginManager = () => {
	var memberId = uni.getStorageSync('openid')

	if (memberId) {
		return true
	} else {
		return false
	}
}



// 6.退出登录
const memberLogoutManager = () => {
	console.log('退出登录=======')
	var that = this
	return new Promise(resolve => {
		// 1. 清空用户access_token
		uni.removeStorageSync('access_token')
		// 2. 清空用户client_id
		uni.removeStorageSync('client_id')
		// 3. 清空expire_in
		uni.removeStorageSync('expire_in')
		// 4. 清空openid
		uni.removeStorageSync('openId')
		// 4. 清空unionId
		uni.removeStorageSync('unionId')
		uni.removeStorageSync('unionid')
		// 5. 清空sessionKey
		uni.removeStorageSync('sessionKey')

		// 4. 清空当前用户信息
		if (getApp().globalData.userId) {
			getApp().globalData.userId = null
		}
		if (getApp().globalData) {
			getApp().globalData = null
		}

		resolve(true)
	})
}




module.exports = {
	wxLoginManager,
	authLogin,
	AccountUserInfo ,
	memberHasLoginManager,
	memberLogoutManager,
}